<template>
  <div class="box_list">
    <!-- 路径面包屑区域 -->
    <el-breadcrumb class="mb15">
      <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 工作区域 -->
    <el-card>
      <!-- 注意 -->
      <el-alert
        show-icon
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
      ></el-alert>
      <!-- 查询区域 -->
      <el-row class="mt15 mb10">
        <el-col :span="24">
          <!-- 选择商品分类 -->
          <span class="cateTitle">
            <i class="el-icon-s-goods"></i> 选择商品分类：
          </span>
          <el-cascader
            style="width: 300px"
            v-model="cateKeys"
            :options="cateData"
            :props="cateProps"
            @change="handleChange"
            size="small"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 具体内容 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="small"
            :disabled="isDisabled"
            @click="addFormManyOnly"
            >添加参数</el-button
          >
          <!--many table列表数据 -->
          <el-table
            :data="manyTableData"
            border
            stripe
            size="mini"
            class="mt15"
          >
            <el-table-column type="expand">
              <!-- 作用域插槽参数选择项 -->
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="tagClose(scope.row, i)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input_style"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else size="small" @click="showInput(scope.row)"
                  >+ 添加选项</el-button
                >
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              label="序号"
              width="50"
              align="center"
            ></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作" width="250px" align="center">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editFormManyOnly(scope.row.attr_id)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="delParamData(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="small"
            :disabled="isDisabled"
            @click="addFormManyOnly"
            >添加属性</el-button
          >
          <!--only table列表数据 -->
          <el-table
            :data="onlyTableData"
            border
            stripe
            size="mini"
            class="mt15"
          >
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  @close="tagClose(scope.row,i)"
                >{{item}}</el-tag>
                <el-input
                  class="input_style"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else size="small" @click="showInput(scope.row)"
                  >+ 添加选项</el-button
                >
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              label="序号"
              width="50"
              align="center"
            ></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作" width="250px" align="center">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editFormManyOnly(scope.row.attr_id)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="delParamData(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加动态参数/静态属性 -->
    <AddForm
      ref="childrenRef"
      @refreshData="refreshMethod"
      :isManyOnly="isManyOnly"
      :threeCateId="threeCateId"
      :activeName="activeName"
    ></AddForm>
    <EditForm
      ref="editChildrenRef"
      @refreshData="refreshMethod"
      :isManyOnly="isManyOnly"
      :editFormData="editFormData"
    ></EditForm>
  </div>
</template>

<script>
import AddForm from "./AddForm";
import EditForm from "./EditForm";
export default {
  components: { AddForm, EditForm },
  data() {
    return {
      //商品分类
      cateData: [],
      cateProps: {
        // 当前的选项的id
        value: "cat_id",
        // 展示的名称
        label: "cat_name",
        // 指定父级与子级的嵌套
        children: "children",
        // 移入显示子级
        expandTrigger: "hover",
        // 选择任意一级
        checkStrictly: true,
      },
      cateKeys: [],
      // tab页默认激活的标签
      activeName: "many",

      // 动态参数列表数据
      manyTableData: [],
      // 静态属性列表数据
      onlyTableData: [],
      //查询的修改动态参数，静态配置数据
      editFormData: {},
      // 参数添加选项输入框和按钮显示隐
    };
  },
  created() {
    this.getCateData();
  },
  methods: {
    //获取商品分类
    getCateData() {
      this.$axios
        .get("categories", { params: { type: 3 } })
        .then((res) => {
          if (res.data.meta.status == 200) {
            this.cateData = res.data.data;
          } else {
            this.$message.error("获取商品分类失败");
            return;
          }
        })
        .catch((error) => {
          console.log(error); //cathch用于处理错误事件
        });
    },
    //监听商品分类选择的变化
    handleChange() {
      // 证明选中的是 三级商品分类
      if (this.cateKeys.length == 3) {
        this.paramsData();
      } else {
        // 证明选中的不是 三级商品分类
        this.cateKeys = [];
        // 将动态参数、静态配置数据列表清空
        this.manyTableData = [];
        this.onlyTableData = [];
        return;
      }
    },
    // tab 标签页点击事件
    handleClick() {
      console.log(this.activeName);
      // 证明选中的是 三级商品分类
      if (this.cateKeys.length == 3) {
        this.paramsData();
      } else {
        // 证明选中的不是 三级商品分类
        this.cateKeys = [];
        return;
      }
    },
    // 获取动态参数、静态配置数据列表
    paramsData() {
      this.$axios
        .get(`categories/${this.threeCateId}/attributes`, {
          params: {
            sel: this.activeName,
          },
        })
        .then((res) => {
          // 动态参数********************************
          if (this.activeName === "many") {
            // 将参数attr_vals选项字符串循环拿到当前选项转化成数组
            res.data.data.forEach((item) => {
              // 判断item.attr_vals是否为空，为空返回[] 否则执行item.attr_vals.split(",");
              item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
              // 向res.data.data item中塞两个对象
              // 控制参数选项按钮和input显示隐藏
              item.inputVisible = false;
              // 输入框的输入值
              item.inputValue = "";
            });
            this.manyTableData = res.data.data;
            //console.log(res.data.data)
          }
          // 静态属性**********************************
          else {
            // 将参数attr_vals选项字符串循环拿到当前选项转化成数组
            res.data.data.forEach((item) => {
              item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
                    // 向res.data.data item中塞两个对象
                       // 控制参数选项按钮和input显示隐藏
              item.inputVisible=false;
                // 输入框的输入值
              item.inputValue=""
            });
            this.onlyTableData = res.data.data;

            console.log(res.data.data);
          }
        })
        .catch((error) => {
          console.log(error); //cathch用于处理错误事件
        });
    },

    // 添加动态参数、静态属性选项 *************************************************************
    showInput(scope) {
      scope.inputVisible = true;
      // 文本框自动获取焦点
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //添加动态参数、静态属性选项 input 操作
    handleInputConfirm(scope) {
      // 判断输入框是否为空
      if (scope.inputValue.trim().length === 0) {
        scope.inputValue = "";
        scope.inputVisible = false;
        return;
      } else {
        // 输入框不为空将值push到当前scope.attr_val中
        scope.attr_vals.push(scope.inputValue.trim());
        // push 后清空输入框
        scope.inputValue = "";
        scope.inputVisible = false;
        // 调用提交参数方法
        this.ggggg(scope);
      }
    },
    // ### 编辑提交参数 请求方法
    ggggg(scope) {
      this.$axios
        .put(`categories/${this.threeCateId}/attributes/${scope.attr_id}`, {
          attr_name: scope.attr_name,
          attr_sel: scope.attr_sel,
          attr_vals: scope.attr_vals.toString(),
        })
        .then((res) => {
          if (res.data.meta.status == 200) {
            this.$message.success("参数选项添加成功");
          } else {
            this.$message.error("参数选项添加失败");
            return;
          }
        })
        .catch((error) => {
          console.log(error); //cathch用于处理错误事件
        });
    },
    // 删除动态参数选项
    tagClose(scope, i) {
      scope.attr_vals.splice(i, 1);
      // 调用提交参数方法
      this.ggggg(scope);
    },

// **********************************************************************************


    // 刷新table数据
    refreshMethod() {
      this.paramsData();
    },
    // 添加动态参数/静态属性
    addFormManyOnly() {
      this.$refs.childrenRef.showDialog();
    },
    // 修改动态参数/静态属性
    editFormManyOnly(id) {
      console.log(this.threeCateId);
      this.$axios
        .get(`categories/${this.threeCateId}/attributes/${id}`, {
          params: {
            attr_sel: this.activeName,
          },
        })
        .then((res) => {
          if (res.data.meta.status == 200) {
            console.log(res);
            this.editFormData = res.data.data;
          } else {
            this.$message.error("获取参数失败");
          }
        })
        .catch((error) => {
          console.log(error); //cathch用于处理错误事件
        });

      this.$refs.editChildrenRef.showDialog();
    },
    // 删除当前参数或配置
    delParamData(scope) {
      console.log(scope);
      this.$msgBox
        .confirm("此操作将永久删除该参数, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then((res) => {
          this.$axios
            .delete(`categories/${scope.cat_id}/attributes/${scope.attr_id}`)
            .then((res) => {
              // console.log(res)
              if (res.data.meta.status == 200) {
                this.$message.success("删除当前参数/属性成功");
                this.paramsData();
              } else {
                return this.$message.error("删除当前参数/属性失败");
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  computed: {
    // 计算属性如果按钮被禁用,则返回true，否则返回false
    isDisabled() {
      if (this.cateKeys.length == 3) {
        return false;
      } else {
        return true;
      }
    },
    //当前选择的商品分类的三级节点id
    threeCateId() {
      if (this.cateKeys.length === 3) {
        return this.cateKeys[2];
      } else {
        return null;
      }
    },
    // 计算添加form标题名称 如果点击是many"动态参数"，若果是only""静态配置"
    isManyOnly() {
      if (this.activeName == "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    },
  },
};
</script>

<style scoped>
.cateTitle {
  color: #e6a23c;
  background: #fdf6ec;
  padding: 7px 10px;
  vertical-align: middle;
  border: 1px solid #dedddc;
  margin-right: 5px;
  border-radius: 4px;
}
.el-tag {
  margin: 5px;
}
.input_style {
  width: 150px;
}
</style>